Array.prototype.removeAt = function(index){
    if( isNaN(index) || index > this.length){return false;}
    this.splice(index,1);
};
var empty_fn = function(){};
setTimeout(function(){
    if(typeof(window['layer']) == "undefined"){
        window['layer'] = {msg:function(msg){alert(msg)}};
    }
},500);

$.util = {
    lang:{
        data:{
            update_success:'更新数据成功',
            save_success:'保存数据成功'
        },
        modal:{
            yes : '确定',
            no  : '取消'
        },
        ajax:{
            error:'提交数据时发生了错误,请重试或联系开发人员'
        },
        form:{
            error:'数据填写不正确或者不完整,请修改后提交'
        },
        page:{
            loading:'加载中...',
            error:'加载失败,请点击重试'
        }
        ,upload:{
            done_photo:'图片已经上传完成',
            please_select_file:'请选择要上传的文件',
            done:'上传已经完成',
            upload_error_retry:'上传文件失败,请重新选择',
            upload_error:'上传文件失败'
        }
    },
    upload:{
        SWF_UPLOAD_QUEUED_DATA:[],
        setting:{
            flash_url : "public/assets/swfup/swfupload.swf",
            upload_url: "",
            post_params: {},
            file_size_limit : "10 MB",
            file_types : "*.*",
            file_types_description : "All Files",
            file_upload_limit : 100,
            file_queue_limit : 0,

            button_image_url: "public/assets/swfup/transparent.png",
            button_width: "150",
            button_height: "30",
            button_placeholder_id: ""
        }
    }
};

;(function($){
    $.fn.checkAll = function(){
        this.on('click',function(){
            var me = $(this);
            var data_check = me.attr('data-check');
            if(!data_check) {data_check = me.attr('data-target')}
            var state = this.checked;
            $(data_check).each(function(){
                this.checked = state;
            });
        })
    };
    $.fn.ajaxLoadByPage = function(ajaxUrl,callback){
        var loadHtml = function(url,me){
            me.html('<p style="line-height: 40px;text-align: center;">加载中...</p>');
            me.attr('load-url',url);
            $.get(url,function(source){
                if(typeof(callback) == "function"){
                    try{
                        callback.call(me,source);
                    }catch (e){}
                }
                me.html(source);
                initEvent(me);
            },'text')
                .error(function(){
                    me.html('');
                    var p = $('<p style="color:#f00;line-height: 40px;text-align: center;"></p>')
                        .appendTo(me);
                    var retry = $('<a href="#"></a>').html($.util.lang.page.error).appendTo(p);
                    retry.on('click',function(){
                        loadHtml(url);
                        return false;
                    });
                    return false;
                });
            return false;
        };
        var loadUrl = function(me){
            loadHtml($(this).attr('href'),me);
        };
        var initEvent = function(me){
            me.find('ul.pagination').find('li>a').click(function(){
                loadUrl.call(this,me);
                return false;
            });

            me.find('input[type=checkbox].checkAll,input[type=checkbox].check-all').checkAll();
        };
        if(ajaxUrl){
            loadHtml(ajaxUrl,$(this));
            return;
        }
        this.each(function(){
            initEvent($(this))
        });
    };
})(jQuery);

;$(function(){
    $('input[type=checkbox].checkAll,input[type=checkbox].check-all').checkAll();
    $('form.data-validate').each(function(){
        var me = $(this);
        var errorWrapper = null;
        var resetError = function(){
                if(errorWrapper != null){
                    errorWrapper.remove();
                    errorWrapper = null;
                }

            },
            showError = function(errorMsg){
                var firstChild = me.children().eq(0);
                if(errorWrapper == null){
                    errorWrapper = $('<div class="alert alert-warning alert-dismissible" role="alert"></div>')
                        .appendTo(me);
                    $('<button type="button" class="close" data-dismiss="alert" aria-label="Close">')
                        .appendTo(errorWrapper).append('<span aria-hidden="true">&times;</span>');
                    errorWrapper.append('<span class="error-str-w"></span>');
                }
                if(me.find('.alert-warning').length == 0) errorWrapper.appendTo(me);
                errorWrapper.find('.error-str-w').html(errorMsg);
            };
        var opt = {
            //表单验证失败时的处理函数
            errorSubmit:function(){
                var errorMsg = me.attr('data-validate-error') || $.util.lang.form.error;
                layer.msg(errorMsg,{
                    offset:'20px'
                });
                return false;
            }
        };
        if(me.attr('post-type') && me.attr('post-type') == 'ajax'){
            //针对 ajax表单提交数据的处理
            opt['submitHandler'] = function(form) {
                resetError();
                var _submit = me.find('[type=submit]');
                _submit.button('loading');
                if(me.data('submitHandler') && typeof(me.data('submitHandler')) == "function"){
                    me.data('submitHandler').call(me,_submit);
                    return false;
                }
                $.post(me.attr('action'),me.serializeArray(),function(json){
                    _submit.button('reset');
                    if(json['code'] == 0){
                        if(me.data('success_call') && typeof(me.data('success_call')) == "function"){
                            me.data('success_call').call(me);
                        }else if(json['data']['url']){
                            location.href=json['data']['url'];
                        }else{
                            layer.msg($.util.lang.data.save_success,{time:1000,end:function(){
                                location.reload();
                            }});
                        }
                    }else{
                        layer.msg(json['msg']);
                    }
                },'json').error(function(){
                        _submit.button('reset');
                        layer.msg($.util.lang.ajax.error);
                    });
            };
        }
        //如果不想显示表单显示错误时的错误处理，删除处理函数
        if(me.attr('validate-error') == 'no') delete opt['errorSubmit'];
        me.validate(opt);//验证表单数据的配置
    });
    var data_call = function(){
        var dateFormat = 'yyyy-MM-dd';
        var me = $(this);
        if(me.attr('date-format')){
            dateFormat = me.attr('date-format');
        }
        var conf = {
            dateFmt:dateFormat,
            skin:'ycm'
        };
        if(me.attr('date-min')){
            conf['minDate'] = me.attr('date-min');
        }
        if(me.attr('date-max')){
            conf['maxDate'] = me.attr('date-max');
        }
        WdatePicker.call(this,conf);
    };
    $('.datetime').on('focus',data_call);
    $('.ajax-post').click(function () {
        var updateAlert = function(msg,r){
            layer.msg(msg,{time:1500});
        };
        var target, query, form;
        var target_form = $(this).attr('target-form');
        var _before = $(this).data('before');
        if(typeof(_before) == "function"){//前置验证
            var ret = true;
            try{
                ret = _before.call(this);
            }catch(e){}
            if(ret === false){
                return false;
            }
        }
        var that = this;
        var nead_confirm = false;
        var null_msg = $(this).attr('data-null') ? $(this).attr('data-null'):'请勾选操作数据';
        if (
            ($(this).attr('type') == 'submit') ||
            (target = $(this).attr('href')) ||
            (target = $(this).attr('url'))
            ) {
            form = $('.' + target_form);
            if ($(this).attr('hide-data') === 'true') {//无数据时也可以使用的功能
                form = $('.hide-data');
                query = form.serialize();
            } else if (target_form != 'no_data' && form.get(0) == undefined) {
                updateAlert(null_msg);
                return false;
            } else if (target_form != 'no_data' && form.get(0).nodeName == 'FORM') {
                if ($(this).hasClass('confirm')) {
                    var confirm_info = $(that).attr('confirm-info');
                    confirm_info=confirm_info?confirm_info:"确认要执行该操作吗?";
                    if (!confirm(confirm_info)) {
                        return false;
                    }
                }
                if ($(this).attr('url') !== undefined) {
                    target = $(this).attr('url');
                } else {
                    target = form.get(0).action;
                }
                query = form.serialize();
            } else if (target_form != 'no_data' && (form.get(0).nodeName == 'INPUT' || form.get(0).nodeName == 'SELECT' || form.get(0).nodeName == 'TEXTAREA')) {
                form.each(function (k, v) {
                    if (v.type == 'checkbox' && v.checked == true) {
                        nead_confirm = true;
                    }
                })
                if (nead_confirm && $(this).hasClass('confirm')) {
                    var confirm_info = $(that).attr('confirm-info');
                    confirm_info=confirm_info?confirm_info:"确认要执行该操作吗?";
                    if (!confirm(confirm_info)) {
                        return false;
                    }
                }
                query = form.serialize();
            } else {
                if ($(this).hasClass('confirm')) {
                    var confirm_info = $(that).attr('confirm-info');
                    confirm_info=confirm_info?confirm_info:"确认要执行该操作吗?";
                    if (!confirm(confirm_info)) {
                        return false;
                    }
                }
                if(target_form == 'no_data'){
                    if($(this).attr('post-data')){
                        query = $(this).attr('post-data');
                    }
                }else{
                    query = form.find('input,select,textarea').serialize();
                }
            }
            if(query=='' && target_form != 'no_data'){
                updateAlert(null_msg,'danger');
                return false;
            }
            $(that).addClass('disabled').attr('autocomplete', 'off').prop('disabled', true);
            $.post(target, query,function (data) {
                $(that).removeClass('disabled').attr('autocomplete', 'on').prop('disabled', false);
                if (data['code'] == 0) {
                    if(data['data'] && data['data']['action'] && data['data']['action'] == 'close'){
                        updateAlert(data.msg, 'success');
                        util.close(window,'success');
                        return false;
                    }
                    if (data['data'] && data['data']['url']) {
                        updateAlert(data.msg + ' 页面即将自动跳转~', 'success');
                    } else {
                        updateAlert(data.msg, 'success');
                    }
                    setTimeout(function () {
                        if (data['data'] && data['data']['url']) {
                            location.href = data['data']['url'];
                        } else {
                            location.reload();
                        }
                    }, 1500);
                } else {
                    updateAlert(data.msg);
                }
            },'json').error(function(){
                    $(that).removeClass('disabled').attr('autocomplete', 'on').prop('disabled', false);
                    updateAlert('发送数据请求失败');
                });
        }
        return false;
    });
    //ajax get请求
    $('.ajax-get').click(function () {
        var updateAlert = function(msg,r){
            layer.msg(msg,{time:1500});
        };
        var target;
        var that = this;
        if ($(this).hasClass('confirm')) {
            if (!confirm('确认要执行该操作吗?')) {
                return false;
            }
        }
        var post_data = '';
        if($(this).attr('post-data')){
            post_data = $(this).attr('post-data');
        }
        if ((target = $(this).attr('href')) || (target = $(this).attr('url'))) {
            $.get(target,post_data,function (data) {
                if (data['code'] == 0) {
                    if (data['data']['url']) {
                        updateAlert(data.msg + ' 页面即将自动跳转~', 'success');
                    } else {
                        updateAlert(data.msg, 'success');
                    }
                    setTimeout(function () {
                        if (data['data']['url']) {
                            location.href = data['data']['url'];
                        } else {
                            location.reload();
                        }
                    }, 1500);
                } else {
                    updateAlert(data.msg);
                }
            },'json').error(function(){
                    updateAlert('发送数据请求失败');
                });

        }
        return false;
    });
    $('[load-model=ajax]').ajaxLoadByPage();
});